package com.boss.salary.service.impl;

import com.boss.common.entity.PageDTO;
import com.boss.common.entity.WfActionDTO;
import com.boss.common.enums.ActionTypeEnum;
import com.boss.common.enums.StatusCodeEnum;
import com.boss.common.service.ICommonService;
import com.boss.common.util.DateUtils;
import com.boss.framework.dto.PaginationDTO;
import com.boss.framework.exception.AppRuntimeException;
import com.boss.salary.constant.SystemDictConstant;
import com.boss.salary.dao.*;
import com.boss.salary.entity.*;
import com.boss.salary.service.*;
import com.boss.salary.vo.AgencySalaryVO;
import com.boss.salary.vo.AgencyVerifyParamVo;
import com.boss.salary.vo.SalaryMonthEndVO;
import com.boss.salary.vo.UnitSalaryReportVO;
import com.boss.salary.workflow.service.ISalaryWorkFlowService;
import com.boss.sys.ca.user.dto.UserDTO;
import com.boss.sys.utils.SysUtils;
import com.singularsys.jep.JepException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class AgencySalaryMultipleServiceImpl implements IAgencySalaryMultipleService {

    /** 引入日志框架常量 */
    private final static Logger logger = LoggerFactory.getLogger(AgencySalaryMultipleServiceImpl.class);

    private static final DateTimeFormatter DTF = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static final String IS_AUDIT = "1";
    private static final String NO_AUDIT = "0";
    private static final String COLUMN_NAME_PREFIX = "s";

    private Class<? extends Object> clazz = null;
    private Method[] methods = null;

    @Autowired
    private ISalaryWorkFlowService iSalaryWorkFlowService;
    @Autowired
    private IFormulaManageService formulaManageService;
    @Autowired
    private IAgencyInfoDao agencyInfoDao;
    @Autowired
    private IAgencySalaryMultipleDao agencySalaryMultipleDao;
    @Autowired
    private ISalaryMonthEndDao salaryMonthEndDao;
    @Autowired
    private IAgencyVerifyDao agencyVerifyDao;
    @Autowired
    private IPersonInfoDao personInfoDao;
    @Autowired
    private IPersonExtDao personExtDao;
    @Autowired
    private IPersonOperateDao personOperateDao;
    @Autowired
    private IAgencySalaryHistoryDao agencySalaryHistoryDao;
    @Autowired
    private ISalaryBasedataDao salaryBaseDateDao;
    @Autowired
    private IFileInfoDao fileInfoDao;
    @Autowired
    private IPersonTypeSalaryDao iPersonTypeSalaryDao;
    @Autowired
    private ISalaryMonthEndSubmitDao salaryMonthEndSubmitDao;
    @Autowired
    private IPersonExtSubmitDao personExtSubmitDao;
    @Autowired
    private IPayMentLockDao iPayMentLockDao;

    @Autowired
    private ICommonService commonService;
    @Autowired
    private IAgencyVerifyService agencyVerifyService;
    @Autowired
    private IGenerateSalaryDataService iGenerateSalaryDataService;
    @Autowired
    private IAgencyInfoService agencyInfoService;

    @Override
    public PageDTO<AgencySalary> queryAgencySalaryPage(PaginationDTO paginationDTO) {
        List<AgencySalary> list = agencySalaryMultipleDao.queryAgencySalaryPage(paginationDTO);
        int total = agencySalaryMultipleDao.queryAgencySalaryTotal();
        PageDTO<AgencySalary> pageDTO = new PageDTO<>();
        pageDTO.setRows(list);
        pageDTO.setTotal(total);
        return pageDTO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveAgencySalary(List<Map<String, Object>> agencyInfoList,
                                 List<Map<String, Object>> salaryBasedataList,
                                 String flag,
                                 String province) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, JepException {
        Class<?> salaryMonthEndVOClass = SalaryMonthEndVO.class;
        // 如果单位数量为1，则是单位挂工资
        if ("agency".equals(flag)) {
            String agencyId = agencyInfoList.get(0).get("id").toString();
            AgencyInfo agency = new AgencyInfo();
            agency.setId(agencyId);
            // 获取该单位下所有的工资项
            Map<String, Object> queryParam = new HashMap<>(1);
            queryParam.put("agencyId", agencyId);
            queryParam.put("province", province);
            List<AgencySalary> list = agencySalaryMultipleDao.queryAgencySalaryInfo(queryParam);
            // 工资项与字段的对应（columnName）关系
            Map<String, String> salaryColumnMap = new HashMap<>(list.size());
            // 如果存在工资项，存储工资项与字段的对应关系
            if (!CollectionUtils.isEmpty(list)) {
                for (AgencySalary agencySalary : list) {
                    String salaryId = agencySalary.getSalaryId();
                    String columnName = agencySalary.getColumnName();
                    salaryColumnMap.put(salaryId, columnName);
                }
            }
            // 删除表中原有的单位与工资项挂接的数据
            agencySalaryMultipleDao.physicsDeleteAgencySalary(queryParam);
            // 保存单位与工资项挂接数据
            for (Map<String, Object> stringObjectMap : salaryBasedataList) {
                String salaryId = String.valueOf(stringObjectMap.get("id"));
                salaryColumnMap.remove(salaryId);
                AgencySalary agencySalary = new AgencySalary();
                agencySalary.setId(SysUtils.generateGuid());
                agencySalary.setCreateTime(String.valueOf(DateUtils.getCurrentTimeStamp()));
                agencySalary.setUpdateTime(String.valueOf(DateUtils.getCurrentTimeStamp()));
                agencySalary.setAgencyId(agencyId);
                agencySalary.setSalaryId(salaryId);
                SalaryBasedata sb = new SalaryBasedata();
                sb.setId(salaryId);
                sb.setMofDivCode(province);
                //获取工资项所有数据
                sb = salaryBaseDateDao.selectById(sb);
                agencySalary.setColumnName(sb.getSalaryCode());
                agencySalary.setIsDeleted(SystemDictConstant.IS_FALSE);
                agencySalary.setMofDivCode(province);
                agencySalaryMultipleDao.saveAgencySalary(agencySalary);
            }
            //剩余得工资项为取消掉得项，将这些项得金额清零
            List<String> removeSalarys = new ArrayList<>(salaryColumnMap.values());
            if(!CollectionUtils.isEmpty(removeSalarys)){
                List<String> agencyIds = Collections.singletonList(agencyId);
               // List<SalaryMonthEndVO> salaryMonthEndVOList = salaryMonthEndDao.selectSalaryMonthEndWithSalaryType(province, agencyIds);
                List<SalaryMonthEndVO> salaryMonthMultipleEndVOList = agencySalaryMultipleDao.selectSalaryMonthEndWithSalaryType(province, agencyIds);
                for(SalaryMonthEndVO salaryMonthEndVO : salaryMonthMultipleEndVOList){
                    for (String column : removeSalarys) {
                        Method setMethod = salaryMonthEndVOClass.getDeclaredMethod("set" + column.substring(0,1).toUpperCase() + column.substring(1), Double.class);
                        setMethod.invoke(salaryMonthEndVO, Double.parseDouble("0"));
                    }
                }
                salaryMonthMultipleEndVOList = formulaManageService.calculateByFormula(province, agencyIds, salaryMonthMultipleEndVOList);
               // salaryMonthEndDao.batchUpdateSalaryMonthEnd(salaryMonthEndVOList);
                agencySalaryMultipleDao.batchUpdateSalaryMonthEnd(salaryMonthMultipleEndVOList);
//                for (int i=0;i<removeSalarys.size();i++){
//                    SalaryBasedata sb=  new SalaryBasedata();
//                    sb.setId(removeSalarys.get(i));
//                    sb.setMofDivCode(province);
//                    sb=salaryBaseDateDao.selectById(sb);
//                    //清楚取消挂接项得工资金额
//                    salaryMonthEndDao.clearSalaryMonthEndByColum(sb.getSalaryCode(),agency);
//                }
            }
        }
        // 如果工资项数量为1，则时工资挂单位
        else if ("salary".equals(flag)) {
            String salaryId = salaryBasedataList.get(0).get("id").toString();
            SalaryBasedata sb=  new SalaryBasedata();
            sb.setId(salaryId);
            sb.setMofDivCode(province);
            sb=salaryBaseDateDao.selectById(sb);
            // 获取该工资项下所有的单位
            Map<String, Object> queryParam = new HashMap<>(1);
            queryParam.put("salaryId", salaryId);
            List<AgencySalary> list = agencySalaryMultipleDao.queryAgencySalaryInfo(queryParam);
            // 工资项与字段的对应（columnName）关系
            Map<String, String> agencyColumnMap = new HashMap<>(list.size());
            // 如果存在单位，存储单位与字段的对应关系
            if (list.size() > 0) {
                for (AgencySalary agencySalary : list) {
                    String agencyId = agencySalary.getAgencyId();
                    String columnName = agencySalary.getColumnName();
                    agencyColumnMap.put(agencyId, columnName);
                }
            }
            // 删除表中原有的单位与工资项挂接的数据
            agencySalaryMultipleDao.physicsDeleteAgencySalary(queryParam);
            // 新增数据
            for (Map<String, Object> stringObjectMap : agencyInfoList) {
                String agencyId = stringObjectMap.get("id").toString();
                //若原单位list里存当前选择单位，则移除，确保agencyColumnMap中保存得是取消掉得单位
                agencyColumnMap.remove(agencyId);
                AgencySalary agencySalary = new AgencySalary();
                agencySalary.setId(SysUtils.generateGuid());
                agencySalary.setCreateTime(String.valueOf(DateUtils.getCurrentTimeStamp()));
                agencySalary.setUpdateTime(String.valueOf(DateUtils.getCurrentTimeStamp()));
                agencySalary.setAgencyId(agencyId);
                agencySalary.setSalaryId(salaryId);
                agencySalary.setColumnName(sb.getSalaryCode());
                agencySalary.setIsDeleted(SystemDictConstant.IS_FALSE);
                agencySalary.setMofDivCode(province);
                agencySalaryMultipleDao.saveAgencySalary(agencySalary);
            }
            //剩余得工资项为取消掉得项，将这些项得金额清零
            List<String> removeAgencys=new ArrayList<>(agencyColumnMap.keySet());
            if(!CollectionUtils.isEmpty(removeAgencys)){
//              查询需要操作的人员工资
               // List<SalaryMonthEndVO> salaryMonthEndVOList = salaryMonthEndDao.selectSalaryMonthEndWithSalaryType(province, removeAgencys);
                List<SalaryMonthEndVO> salaryMonthMultipleEndVOList = agencySalaryMultipleDao.selectSalaryMonthEndWithSalaryType(province, removeAgencys);
                String column = sb.getSalaryCode();
//              将不再挂接项都设置为0
                for(SalaryMonthEndVO salaryMonthEndVO : salaryMonthMultipleEndVOList){
                    Method setMethod = salaryMonthEndVOClass.getDeclaredMethod("set" + column.substring(0,1).toUpperCase() + column.substring(1), Double.class);
                    setMethod.invoke(salaryMonthEndVO, Double.parseDouble("0"));
                }
                salaryMonthMultipleEndVOList = formulaManageService.calculateByFormula(province, removeAgencys, salaryMonthMultipleEndVOList);
                //salaryMonthEndDao.batchUpdateSalaryMonthEnd(salaryMonthEndVOList);
                agencySalaryMultipleDao.batchUpdateSalaryMonthEnd(salaryMonthMultipleEndVOList);
//                for (int i=0;i<removeAgencys.size();i++){
//                    AgencyInfo agency=  new AgencyInfo();
//                    agency.setId(removeAgencys.get(i));
//                    //清楚取消挂接项得工资金额
//                    salaryMonthEndDao.clearSalaryMonthEndByColum(sb.getSalaryCode(),agency);
//                }
            }
        }


    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateAgencySalary(AgencySalary agencySalary) {
        agencySalary.setUpdateTime(String.valueOf(DateUtils.getCurrentTimeStamp()));
        agencySalaryMultipleDao.updateAgencySalary(agencySalary);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAgencySalary(String id) {
        agencySalaryMultipleDao.deleteAgencySalary(id);
    }

    @Override
    public List<AgencySalary> queryAgencySalaryInfo(Map<String, Object> queryParam) {
        return agencySalaryMultipleDao.queryAgencySalaryInfo(queryParam);
    }

    @Override
    public PageDTO<Map<String, Object>> getUnitSalaryReportPage(PaginationDTO paginationDTO,
                                                                String agencyId,
                                                                String flag,
                                                                Map<String, Object> condition,String mofDivCode) throws AppRuntimeException {
        List<Map<String, Object>> result = Collections.emptyList();
        PageDTO<Map<String, Object>> pageDTO = new PageDTO<>();
        pageDTO.setRows(result);
        pageDTO.setTotal(0);
//        查询当前月份，送审状态及工资变动状态
        Map<String,Object> stateMap = agencyVerifyDao.selectStateByAgencyIds(agencyId,"salary_month","is_submit_in_agency");
        if(CollectionUtils.isEmpty(stateMap)){
            return pageDTO;
        }
//        当月月份
        String salaryMonth = String.valueOf(stateMap.get("salary_month"));
//        判断当前处于哪一个tab页
        if(!"all".equals(flag)){
            String submitState = String.valueOf(stateMap.get("is_submit_in_agency"));
            // 如果是未送审页签，查看未送审和撤回的数据
            if (SystemDictConstant.NO_SUBMIT.equals(flag)) {
                if (!SystemDictConstant.NO_SUBMIT.equals(submitState) && !SystemDictConstant.REVOKE.equals(submitState)) {
                    return pageDTO;
                }
            } else{
                if(!flag.equals(submitState)){
                    return pageDTO;
                }
            }
        }
        List<String> personTypes=new ArrayList<>();
//        获取当月工资字段名
        Object salaryType = condition.get("salaryType");
        if (!StringUtils.isEmpty(salaryType)) {
            personTypes.add(salaryType.toString());
        }else {
            personTypes = iPersonTypeSalaryDao.getAllPersonTypeByAgencyId(agencyId);
        }
        List<PersonTypeSalary> currentcolumnList=iPersonTypeSalaryDao.getInfoByPersonTypes4Unit(personTypes,mofDivCode);
        if(CollectionUtils.isEmpty(currentcolumnList)){
            throw new AppRuntimeException("当前机构未挂接工资项！");
        }
        List<String> salaryColumns = currentcolumnList.stream().map(PersonTypeSalary::getColumnName).collect(Collectors.toList());
        List<String> salaryIds = currentcolumnList.stream().map(PersonTypeSalary::getSalaryId).collect(Collectors.toList());
//获取当月salaryID对应字段名map
        Map<String,String> currentSalaryIdJoinColumnMap = currentcolumnList.stream()
                .collect(Collectors.toMap(PersonTypeSalary::getSalaryId, PersonTypeSalary::getColumnName));
//查询编报数据
        List<Map<String, Object>> salaryMonthEndDatas = agencySalaryMultipleDao.selectUnitSalaryReportPage(
                paginationDTO, agencyId, salaryIds, salaryMonth, currentSalaryIdJoinColumnMap, condition, mofDivCode);
        if (!CollectionUtils.isEmpty(salaryMonthEndDatas)) {
            int[] index = {1};
            result = salaryMonthEndDatas.stream().peek(salaryMonthEndData -> {
                if(SystemDictConstant.IS_TRUE.toString().equals(String.valueOf(salaryMonthEndData.get("different")))){
                    Map<String,Object> salaryHistory = new HashMap<>(salaryMonthEndData);
                    salaryHistory.put("currentMonth", salaryHistory.get("currentMonth_history"));
                    for(String salaryId : salaryIds){
                        String columnName = currentSalaryIdJoinColumnMap.get(salaryId);
                        salaryHistory.put(columnName, salaryMonthEndData.get(columnName + "_history"));
                        salaryHistory.put(columnName + "_history", salaryMonthEndData.get(columnName));
                    }
                    salaryMonthEndData.put("children", Collections.singletonList(salaryHistory));
                }
                salaryMonthEndData.put("index",index[0]++);
            }).collect(Collectors.toList());
            int total = agencySalaryMultipleDao.selectUnitSalaryReportTotal(agencyId, condition,mofDivCode);
//计算各个工资项合计值
//            Map<String, Object> salaryMonthEndSum = agencySalaryDao.selectSalaryMonthEndSum(
//                    agencyId, SystemDictConstant.IS_FALSE, salaryColumns, condition,mofDivCode);
//            salaryMonthEndSum.put("personName", "合计");
//            result.add(0, salaryMonthEndSum);
//            设置返回值
            pageDTO.setRows(result);
            pageDTO.setTotal(total);
        }
        return pageDTO;
    }

    @Override
    public int selectSalaryChangePersonNum(UserDTO userDTO,String agencyId,String isThirtenn, Map<String, Object> queryParam,int is_submit) {
        List<Map<String, Object>> result = Collections.emptyList();
        PageDTO<Map<String, Object>> pageDTO = new PageDTO<>();
        pageDTO.setRows(result);
        pageDTO.setTotal(0);
//        查询当前月份，送审状态及工资变动状态
        Map<String,Object> stateMap = agencyVerifyDao.selectStateByAgencyId(agencyId,isThirtenn,"salary_month","is_submit_in_agency");
//        当月月份
        String salaryMonth = String.valueOf(stateMap.get("salary_month"));
//        上月月份
        String lastSalaryMonth = LocalDate.parse(salaryMonth+"-01", DateTimeFormatter.ofPattern("yyyy-MM-dd"))
                .minusMonths(1).format(DateTimeFormatter.ofPattern("yyyy-MM"));
//        获取当月工资字段名
        List<AgencySalaryVO> currentcolumnList = agencySalaryMultipleDao.selectColumnName(userDTO);
        if(CollectionUtils.isEmpty(currentcolumnList)){
            throw new AppRuntimeException("当前机构未挂接工资项！");
        }
        List<String> salaryColumns = currentcolumnList.stream().map(AgencySalaryVO::getColumnName).collect(Collectors.toList());
        List<String> salaryIds = currentcolumnList.stream().map(AgencySalaryVO::getSalaryId).collect(Collectors.toList());
        //获取上月工资字段名
//        List<AgencySalaryVO> lastColumnList = agencySalaryDao.selectLastColumnName(agencyId, salaryIds, lastSalaryMonth);
        //获取当月salaryID对应字段名map
        Map<String,String> currentSalaryIdJoinColumnMap = currentcolumnList.stream()
                .collect(Collectors.toMap(AgencySalaryVO::getSalaryId, AgencySalaryVO::getColumnName));
        //获取上月salaryID对应字段名map
//        Map<String,String> lastSalaryIdJoinColumnMap = lastColumnList.stream()
//                .collect(Collectors.toMap(AgencySalaryVO::getSalaryId, AgencySalaryVO::getColumnName));
        //查询编报数据
        if(is_submit==1) {//查询上报数据
            int personNum = agencySalaryMultipleDao.selectSalaryChangePersonNumOnSubmit(
                    agencyId, salaryIds, salaryMonth, lastSalaryMonth, currentSalaryIdJoinColumnMap, null, queryParam);
            return personNum;
        }else{//查询未上报数据
            int personNum = agencySalaryMultipleDao.selectSalaryChangePersonNum(
                    agencyId, salaryIds, salaryMonth, lastSalaryMonth, currentSalaryIdJoinColumnMap, null, queryParam);
            return personNum;
        }
    }

    @Override
    public PageDTO<Map<String, Object>> getUnitAuditPage(PaginationDTO paginationDTO,
                                                                String agencyId,

                                                                String flag,
                                                                Map<String, Object> condition,UserDTO userDTO,String menuid) throws AppRuntimeException {
        List<Map<String, Object>> result = Collections.emptyList();
        PageDTO<Map<String, Object>> pageDTO = new PageDTO<>();
        pageDTO.setRows(result);
        pageDTO.setTotal(0);
        List<String> bizKeys = new ArrayList<>();
        WfActionDTO wfActionDTO = new WfActionDTO();
        // 菜单id
        wfActionDTO.setMenuguid(menuid);

// 待办
        if (SystemDictConstant.NO_SUBMIT.equals(flag)) {
            logger.info("===查询待办Begin====");
            wfActionDTO.setStatus(StatusCodeEnum.TODO.getCode());
            //bizKeys = iSalaryWorkFlowService.queryWorkflowInfo(userDTO,wfActionDTO);
            bizKeys = iSalaryWorkFlowService.queryWorkflowInfoMultiple(userDTO,wfActionDTO);

            logger.info("====查询待办End === " + bizKeys);
        }
        // 已办
        else if (SystemDictConstant.IS_SUBMIT.equals(flag)) {
            logger.info("===查询已办Begin====");
            // 获取已办
            wfActionDTO.setStatus(StatusCodeEnum.FINISHED.getCode());
            //bizKeys = iSalaryWorkFlowService.queryWorkflowInfo(userDTO,wfActionDTO);
            bizKeys = iSalaryWorkFlowService.queryWorkflowInfoMultiple(userDTO,wfActionDTO);
            // 获取曾经办数据
            wfActionDTO.setStatus(StatusCodeEnum.ONCE_FINISHED.getCode());
            //List<String> onceBizKeys = iSalaryWorkFlowService.queryWorkflowInfo(userDTO,wfActionDTO);
            List<String> onceBizKeys = iSalaryWorkFlowService.queryWorkflowInfoMultiple(userDTO,wfActionDTO);



            if (StringUtils.isEmpty(bizKeys)) {
                bizKeys = new ArrayList<>();
            }
            if (!StringUtils.isEmpty(onceBizKeys) && onceBizKeys.size() > 0) {
                bizKeys.addAll(onceBizKeys);
            }
            logger.info("====查询已办End === " + bizKeys);
        }
        if ("-1".equals(flag)) {
            logger.info("===查询被退回Begin====");
            wfActionDTO.setStatus(StatusCodeEnum.BESENDBACK.getCode());
           //bizKeys = iSalaryWorkFlowService.queryWorkflowInfo(userDTO,wfActionDTO);
            bizKeys = iSalaryWorkFlowService.queryWorkflowInfoMultiple(userDTO,wfActionDTO);


            logger.info("====查询被退回End === " + bizKeys);
        }


        Map<String,Object> stateMap = agencyVerifyDao.selectStateByAgencyIdAndBizkey1(agencyId,bizKeys,flag,
                "salary_month","is_submit_in_agency","salary_verified_in_agency_code","is_salary_change","is_salary_submit");
        if(CollectionUtils.isEmpty(stateMap)){
            return pageDTO;
        }
        String salaryMonth = String.valueOf(stateMap.get("salary_month"));


//        获取当月工资字段名
        List<String> personTypes=new ArrayList<>();
//        获取当月工资字段名
        Object salaryType = condition.get("salaryType");
        if (!StringUtils.isEmpty(salaryType)) {
            personTypes.add(salaryType.toString());
        }else {
            personTypes = iPersonTypeSalaryDao.getAllPersonTypeByAgencyId(agencyId);
        }
        List<PersonTypeSalary> currentcolumnList=iPersonTypeSalaryDao.getInfoByPersonTypes4Unit(personTypes,userDTO.getProvince());
        if(CollectionUtils.isEmpty(currentcolumnList)){
            throw new AppRuntimeException("当前机构未挂接工资项！");
        }
        List<String> salaryColumns = currentcolumnList.stream().map(PersonTypeSalary::getColumnName).collect(Collectors.toList());
        List<String> salaryIds = currentcolumnList.stream().map(PersonTypeSalary::getSalaryId).collect(Collectors.toList());
//获取当月salaryID对应字段名map
        Map<String,String> currentSalaryIdJoinColumnMap = currentcolumnList.stream()
                .collect(Collectors.toMap(PersonTypeSalary::getSalaryId, PersonTypeSalary::getColumnName));
        //查询最大批次数
        AgencyVerify agencyVerify=agencySalaryMultipleDao.getIsThirteen(agencyId);
        //查询编报数据
        List<Map<String, Object>> salaryMonthEndDatas = agencySalaryMultipleDao.selectUnitAuditPage(
                paginationDTO, agencyId,agencyVerify.getIsThirteen(),salaryIds, salaryMonth, currentSalaryIdJoinColumnMap,  condition,userDTO.getProvince());
        if (!CollectionUtils.isEmpty(salaryMonthEndDatas)) {
            int[] index = {1};
//            获取当前机构的工资变动状态
            int[] different = {0};
            result = salaryMonthEndDatas.stream().peek(salaryMonthEndData -> {
//                工资照比上个月有变动
                if(SystemDictConstant.IS_TRUE.toString().equals(String.valueOf(salaryMonthEndData.get("different")))){
                    Map<String,Object> salaryHistory = new HashMap<>(salaryMonthEndData);
                    salaryHistory.put("currentMonth", salaryHistory.get("currentMonth_history"));
                    for(String salaryId : salaryIds){
                        String columnName = currentSalaryIdJoinColumnMap.get(salaryId);
                        salaryHistory.put(columnName, salaryMonthEndData.get(columnName + "_history"));
                        salaryHistory.put(columnName + "_history", salaryMonthEndData.get(columnName));
                    }
                    salaryMonthEndData.put("children", Collections.singletonList(salaryHistory));
                    different[0] = 1;
                }
                salaryMonthEndData.put("index",index[0]++);
            }).collect(Collectors.toList());
            int total = agencySalaryMultipleDao.selectUnitAuditTotal(agencyId, condition,userDTO.getProvince());
//计算各个工资项合计值
            Map<String, Object> salaryMonthEndSum = agencySalaryMultipleDao.selectSalaryMonthEndSum(
                    agencyId, SystemDictConstant.IS_TRUE, salaryColumns, condition,userDTO.getProvince());
            salaryMonthEndSum.put("index", "合计");
            result.add(0, salaryMonthEndSum);
//            设置返回值
            pageDTO.setRows(result);
            pageDTO.setTotal(total);

            //当前机构工资变动状态
//            int isSalaryChange = Integer.parseInt(String.valueOf(stateMap.get("is_salary_change")));
////            判断机构的工资变动状态是否改变，改变则更新状态到agency_salary表
//            if (isSalaryChange <= 0) {
//                if(paginationDTO.getCurrpage() == 1 && different[0] != isSalaryChange){
//                    AgencyVerify agencyVerify = new AgencyVerify();
//                    agencyVerify.setAgencyId(agencyId);
//                    agencyVerify.setUpdateTime(String.valueOf(DateUtils.getCurrentTimeStamp()));
//                    agencyVerify.setIsSalaryChange(different[0]);
//                    agencyVerifyDao.updateAgencyState(agencyVerify);
//                }
//            }
        }
        return pageDTO;
    }

    @Override
    public PageDTO<Map<String, Object>> getUnitSalarySubmitReportPage(UserDTO userDTO, PaginationDTO paginationDTO, Map<String, Object> queryParam) throws AppRuntimeException {
        boolean currentNode = false;
        // 查询工作流待办数量
        String agencyId = queryParam.get("agencyId").toString();
        List<String> bizKeys = new ArrayList<>();
        WfActionDTO wfActionDTO = new WfActionDTO();
        // 菜单id
        wfActionDTO.setMenuguid(queryParam.get("menuid").toString());
        if ("0".equals(queryParam.get("flag"))) {
            logger.info("===查询待办Begin====");
            wfActionDTO.setStatus(StatusCodeEnum.TODO.getCode());
            //bizKeys = iSalaryWorkFlowService.queryWorkflowInfo(userDTO,wfActionDTO);
            bizKeys = iSalaryWorkFlowService.queryWorkflowInfoMultiple(userDTO,wfActionDTO);

            // 获取该单位在审核表对应得id
            if (!StringUtils.isEmpty(bizKeys) && bizKeys.size() > 0) {
                AgencyVerify agencyVerify = agencyVerifyDao.getInfoByAgencyId(agencyId);
                if (bizKeys.contains(agencyVerify.getBizKey())) {
                    currentNode = true;
                }
            }
        } else if ("1".equals(queryParam.get("flag"))) {
            logger.info("===查询已上报Begin====");
            // 获取已办数据
            wfActionDTO.setStatus(StatusCodeEnum.FINISHED.getCode());
            //bizKeys = iSalaryWorkFlowService.queryWorkflowInfo(userDTO,wfActionDTO);
            bizKeys = iSalaryWorkFlowService.queryWorkflowInfoMultiple(userDTO,wfActionDTO);

            // 获取曾经办数据
            //wfActionDTO.setStatus(StatusCodeEnum.ONCE_FINISHED.getCode());
            //List<String> onceBizKeys = iSalaryWorkFlowService.queryWorkflowInfo(userDTO,wfActionDTO);
            if (StringUtils.isEmpty(bizKeys)) {
                bizKeys = new ArrayList<>();
            }
            /*if (!StringUtils.isEmpty(onceBizKeys) && onceBizKeys.size() > 0) {
                bizKeys.addAll(onceBizKeys);
            }*/
            // 获取该单位在审核表对应得id
            if (!StringUtils.isEmpty(bizKeys) && bizKeys.size() > 0) {
                AgencyVerify agencyVerify = agencyVerifyDao.getInfoByAgencyId(agencyId);
                if (bizKeys.contains(agencyVerify.getBizKey())) {
                    currentNode = true;
                }
            }
        } else if ("-1".equals(queryParam.get("flag"))) {
            logger.info("===查询被退回Begin====");
            wfActionDTO.setStatus(StatusCodeEnum.BESENDBACK.getCode());
            //bizKeys = iSalaryWorkFlowService.queryWorkflowInfo(userDTO,wfActionDTO);
            bizKeys = iSalaryWorkFlowService.queryWorkflowInfoMultiple(userDTO,wfActionDTO);

            // 获取该单位在审核表对应得id
            if (!StringUtils.isEmpty(bizKeys) && bizKeys.size() > 0) {
                AgencyVerify agencyVerify = agencyVerifyDao.getInfoByAgencyId(agencyId);
                if (bizKeys.contains(agencyVerify.getBizKey())) {
                    currentNode = true;
                }
            }
        }
        List<Map<String, Object>> list = new ArrayList<>();
        int total = 0;
        if (currentNode) {
            Map<String,Object> stateMap = agencyVerifyDao.selectStateByAgencyId(agencyId,"0", "salary_month");
            String salaryMonth = String.valueOf(stateMap.get("salary_month"));
            //  上月月份
            String lastSalaryMonth = LocalDate.parse(salaryMonth+"-01", DateTimeFormatter.ofPattern("yyyy-MM-dd"))
                    .minusMonths(1).format(DateTimeFormatter.ofPattern("yyyy-MM"));
            //  获取当月工资字段名
            List<AgencySalaryVO> currentcolumnList = agencySalaryMultipleDao.selectColumnName(userDTO);
            List<String> salaryIds = currentcolumnList.stream().map(AgencySalaryVO::getSalaryId).collect(Collectors.toList());
            //获取当月salaryID对应字段名map
            Map<String,String> currentSalaryIdJoinColumnMap = currentcolumnList.stream()
                    .collect(Collectors.toMap(AgencySalaryVO::getSalaryId, AgencySalaryVO::getColumnName));
            list = agencySalaryMultipleDao.selectUnitSalarySubmitReportPage(paginationDTO, agencyId, salaryIds, salaryMonth, currentSalaryIdJoinColumnMap, queryParam);
            if (!StringUtils.isEmpty(list) && list.size() > 0) {
                Map<String, Object> sumMoney = agencySalaryMultipleDao.selectUnitSalarySubmitReportSum(agencyId, salaryIds, salaryMonth, currentSalaryIdJoinColumnMap, queryParam);
                list.add(0, sumMoney);
            }
            total = agencySalaryMultipleDao.selectUnitSalarySubmitReportTotal(agencyId, lastSalaryMonth, queryParam);
        }
        PageDTO<Map<String, Object>> pageDTO = new PageDTO<>();
        pageDTO.setRows(list);
        pageDTO.setTotal(total);
        return pageDTO;
    }

    @Override
    public String selectSubmitSalarySum(UserDTO userDTO, Map<String, Object> queryParam) throws AppRuntimeException {
        boolean currentNode = false;
        // 查询工作流待办数量
        String agencyId = queryParam.get("agencyId").toString();
        List<String> bizKeys = new ArrayList<>();
        WfActionDTO wfActionDTO = new WfActionDTO();
        // 菜单id
        wfActionDTO.setMenuguid(queryParam.get("menuid").toString());
        if ("0".equals(queryParam.get("flag"))) {
            currentNode = true;
        } else if ("1".equals(queryParam.get("flag"))) {
            logger.info("===查询已上报Begin====");
            wfActionDTO.setStatus(StatusCodeEnum.FINISHED.getCode());
            //bizKeys = iSalaryWorkFlowService.queryWorkflowInfo(userDTO,wfActionDTO);
            bizKeys = iSalaryWorkFlowService.queryWorkflowInfoMultiple(userDTO,wfActionDTO);

            // 获取该单位在审核表对应得id
            if (!StringUtils.isEmpty(bizKeys) && bizKeys.size() > 0) {
                AgencyVerify agencyVerify = agencyVerifyDao.getInfoByAgencyId(agencyId);
                if (bizKeys.contains(agencyVerify.getBizKey())) {
                    currentNode = true;
                }
            }
        } else if ("-1".equals(queryParam.get("flag"))) {
            logger.info("===查询被退回Begin====");
            wfActionDTO.setStatus(StatusCodeEnum.BESENDBACK.getCode());
            //bizKeys = iSalaryWorkFlowService.queryWorkflowInfo(userDTO,wfActionDTO);
            bizKeys = iSalaryWorkFlowService.queryWorkflowInfoMultiple(userDTO,wfActionDTO);

            // 获取该单位在审核表对应得id
            if (!StringUtils.isEmpty(bizKeys) && bizKeys.size() > 0) {
                AgencyVerify agencyVerify = agencyVerifyDao.getInfoByAgencyId(agencyId);
                if (bizKeys.contains(agencyVerify.getBizKey())) {
                    currentNode = true;
                }
            }
        }
        if (currentNode) {
            String columnName = "s1";//agencySalaryDao.selectReallySendSalaryColumnName(queryParam.get("agencyId").toString());
            queryParam.put("salaryCloumnName", columnName);
            if (StringUtils.isEmpty(columnName)) {
                return "0.00";
            }

            return agencySalaryMultipleDao.selectSubmitSalarySum(queryParam);
            //salaryMonthEndDao.selectSubmitSalarySum(queryParam);
        }
        return "0.00";
    }

    @Override
    public List<String> getColumnName(String agencyId,Map<String,Object> condition,UserDTO userDTO) {
        int isCompute = 1;
        List<String> personTypes=new ArrayList<>();
        Object salaryType = condition.get("salaryType");
        if (!StringUtils.isEmpty(salaryType)) {
            personTypes.add(salaryType.toString());
        }else {
            personTypes = iPersonTypeSalaryDao.getAllPersonTypeByAgencyId(agencyId);
        }
        //获取人员类型查询工资项
        List<PersonTypeSalary> columnNameList=iPersonTypeSalaryDao.getInfoByPersonTypes4Unit(personTypes,userDTO.getProvince());
       // List<AgencySalaryVO> columnNameList = agencySalaryDao.selectColumnName(agencyId);
        return columnNameList.stream().map(PersonTypeSalary -> {
            if(PersonTypeSalary.getIsCompute().equals(isCompute)){
                return PersonTypeSalary.getColumnName() + "_compute";
            }else{
                return PersonTypeSalary.getColumnName();
            }
        }).collect(Collectors.toList());
    }

    @Override
    public List<Map<String, Object>> getSalaryName(String mof_div_code) {
        return iPersonTypeSalaryDao.selectSalaryName(mof_div_code);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUnitSalaryReport(List<SalaryMonthEnd> data,UserDTO userDto ) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        for (SalaryMonthEnd salaryMonthEnd : data) {
            salaryMonthEnd.setMofDivCode(userDto.getProvince());
            if (StringUtils.isEmpty(salaryMonthEnd.getId())) {
               // salaryMonthEndDao.insertSalaryMonthEndDao(salaryMonthEnd);
                agencySalaryMultipleDao.insertSalaryMonthEndDao(salaryMonthEnd);
            } else {
               // salaryMonthEndDao.updateSalaryMonthEndDao(salaryMonthEnd);
                agencySalaryMultipleDao.updateSalaryMonthEndDao(salaryMonthEnd);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void rejectEditUnitSalaryReport(String province,SalaryMonthEnd data) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
//        查询当前月份
        Map<String,Object> stateMap = agencyVerifyDao.selectStateByAgencyId(data.getAgencyId(),"0","salary_month");
//        当月月份
        String salaryMonth = String.valueOf(stateMap.get("salary_month"));
//        上月月份
        String lastSalaryMonth = LocalDate.parse(salaryMonth+"-01", DateTimeFormatter.ofPattern("yyyy-MM-dd"))
                .minusMonths(1).format(DateTimeFormatter.ofPattern("yyyy-MM"));
//        获取上月对应当月的工资项字段名
        List<Map<String, Object>> currentAndHistoryColumns = agencySalaryHistoryDao.selectSalaryColumnAndName(province,data.getAgencyId(), lastSalaryMonth);
        Map<String, Object> historyColumnJoinSalaryIdMap = new HashMap<>();
        Map<String, Object> salaryIdJoinCurrentColumnMap = new HashMap<>();
        List<String> historyColumns = new ArrayList<>();
        List<String> currentColumns = new ArrayList<>();
        for(Map<String,Object> column : currentAndHistoryColumns){
            historyColumns.add(String.valueOf(column.get("columnName")));
            currentColumns.add(String.valueOf(column.get("currentColumn")));
            historyColumnJoinSalaryIdMap.put(String.valueOf(column.get("columnName")),column.get("salaryId"));
            salaryIdJoinCurrentColumnMap.put(String.valueOf(column.get("salaryId")),column.get("currentColumn"));
        }
        //获取月初工资数据
        SalaryHistory salaryHistory = agencySalaryMultipleDao.selectSalaryHistoryDataByPersonId(data.getAgencyId(), data.getPersonId(), lastSalaryMonth, historyColumns);
//        赋值
        Class<?> _SalaryMonthEnd = data.getClass();
        Class<?> _SalaryHistory = salaryHistory.getClass();
        for (String name : historyColumns) {
            Method getMethod = _SalaryHistory.getMethod("get" + name.substring(0, 1).toUpperCase() + name.substring(1));
            String salaryId = String.valueOf(historyColumnJoinSalaryIdMap.get(name));
            String currentColumn = String.valueOf(salaryIdJoinCurrentColumnMap.get(salaryId));
            Method setMethod = _SalaryMonthEnd.getMethod("set" + currentColumn.substring(0, 1).toUpperCase() + currentColumn.substring(1), Double.class);
            Double value = Double.parseDouble(String.valueOf(getMethod.invoke(salaryHistory)));
            setMethod.invoke(data, value);
        }
        data.setColumnNames(String.join(",", currentColumns));
        if (StringUtils.isEmpty(data.getId())) {
//            新增
            agencySalaryMultipleDao.insertSalaryMonthEndDao(data);
            //salaryMonthEndDao.insertSalaryMonthEndDao(data);
        } else {
//            修改
            agencySalaryMultipleDao.updateSalaryMonthEndDao(data);
            //salaryMonthEndDao.updateSalaryMonthEndDao(data);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitUnitSalaryReport(AgencyVerifyParamVo agencyVerifyParamVo, UserDTO userDto) {
        // 执行工作流
        // 获取单位审核信息
        AgencyVerify agencyVerify = agencyVerifyDao.getInfoByAgencyIds(agencyVerifyParamVo.getAgencyId());
        // 单位上报录入流程
        logger.info("==== 工资编报送审工作流 Begin ====");
        WfActionDTO<AgencyVerify> wfActionDTO = new WfActionDTO();
        wfActionDTO.setMenuguid(agencyVerifyParamVo.getMenuid());
        // 单位撤销
        if (SystemDictConstant.REVOKE.equals(String.valueOf(agencyVerify.getIsSubmitInAgency()))) {
            // 送审
            wfActionDTO.setActionType(ActionTypeEnum.WF_AUDIT.getActionTypeCode());
        }
        // 被退回
         else if(SystemDictConstant.IS_REJECT.equals(String.valueOf(agencyVerify.getIsSubmitInAgency()))) {
             // 送审
            wfActionDTO.setActionType(ActionTypeEnum.WF_AUDIT.getActionTypeCode());
        }
         // 未送审
         else if (SystemDictConstant.NO_SUBMIT.equals(String.valueOf(agencyVerify.getIsSubmitInAgency()))) {
            // 录入并送审
            wfActionDTO.setActionType(ActionTypeEnum.WF_INPUT_AUDIT.getActionTypeCode());
        }
        wfActionDTO.setBizDatas(agencyVerify);
        wfActionDTO.setBizKeyName("bizKey");
        //iSalaryWorkFlowService.doSalaryFlow(userDto, wfActionDTO);
        iSalaryWorkFlowService.doSalaryFlowMultiple(userDto, wfActionDTO);
        logger.info("==== 工资编报送审工作流 End ====");
        // 修改表状态
        LocalDateTime dateTime = LocalDateTime.now();
        String updateTime = dateTime.format(DTF);
        agencyVerify.setUpdateTime(updateTime);
        agencyVerify.setIsSubmitInAgency(Integer.parseInt(SystemDictConstant.IS_SUBMIT));
        boolean ischange=false;
        try {
            ischange=agencyVerifyService.checkAgencyIsChanged(agencyVerifyParamVo.getAgencyId());
           int personNum =selectSalaryChangePersonNum(userDto, agencyVerifyParamVo.getAgencyId(),"0",null ,0);
           if(personNum>0){
               ischange=true;
           }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(ischange){
            agencyVerify.setIsSalaryChange(SystemDictConstant.IS_TRUE);
        }else{
            agencyVerify.setIsSalaryChange(SystemDictConstant.IS_FALSE);
        }
        agencyVerifyDao.updateAgencyState(agencyVerify,userDto.getProvince());
    }

    /**
     * 一岗送财政
     * @param agencyVerifyParamVo
     * @param userDto
     */
    @Override
    public void submitUnitSalaryReportOne(AgencyVerifyParamVo agencyVerifyParamVo, UserDTO userDto) throws Exception{
        // 执行工作流
        // 获取单位审核信息
        AgencyVerify agencyVerify = agencyVerifyDao.getInfoByAgencyId(agencyVerifyParamVo.getAgencyId());

        WfActionDTO<AgencyVerify> wfActionDTO = new WfActionDTO();
        wfActionDTO.setMenuguid(agencyVerifyParamVo.getMenuid());
        // 单位撤销
        if (SystemDictConstant.REVOKE.equals(String.valueOf(agencyVerify.getIsSubmitInAgency()))) {
            // 送审
            wfActionDTO.setActionType(ActionTypeEnum.WF_AUDIT.getActionTypeCode());
        }
        // 被退回
        else if(SystemDictConstant.IS_REJECT.equals(String.valueOf(agencyVerify.getIsSubmitInAgency()))) {
            // 送审
            wfActionDTO.setActionType(ActionTypeEnum.WF_AUDIT.getActionTypeCode());
        }
        // 未送审
        else if (SystemDictConstant.NO_SUBMIT.equals(String.valueOf(agencyVerify.getIsSubmitInAgency()))) {
            // 录入并送审
            wfActionDTO.setActionType(ActionTypeEnum.WF_INPUT_AUDIT.getActionTypeCode());
        }
        wfActionDTO.setBizDatas(agencyVerify);
        wfActionDTO.setBizKeyName("bizKey");

        // 修改表状态
        LocalDateTime dateTime = LocalDateTime.now();
        String updateTime = dateTime.format(DTF);
        agencyVerify.setUpdateTime(updateTime);
        //一岗送财政直接修改上报状态
        agencyVerify.setIsSubmitInAgency(Integer.parseInt(SystemDictConstant.IS_SUBMIT));
        agencyVerify.setIsSalarySubmit(Integer.parseInt(SystemDictConstant.IS_SUBMIT));
        boolean ischange=false;
        try {
            ischange=agencyVerifyService.checkAgencyIsChanged(agencyVerifyParamVo.getAgencyId());
            int salaryChangePersonNumersonNum =selectSalaryChangePersonNum(userDto, agencyVerifyParamVo.getAgencyId(),"0",null ,0);
            if(salaryChangePersonNumersonNum>0){
                ischange=true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        if(ischange){
            agencyVerify.setIsSalaryChange(SystemDictConstant.IS_TRUE);
        }else{
            agencyVerify.setIsSalaryChange(SystemDictConstant.IS_FALSE);
        }
        List<String> agencyIds=new ArrayList<>();
        agencyIds.add(agencyVerifyParamVo.getAgencyId());
        //上报时先清空该单位上报数据
        salaryMonthEndSubmitDao.batchPhysicalDeleteSalaryMonthSubmits(userDto.getProvince(), agencyIds,agencyVerify.getIsThirteen());
        personExtSubmitDao.batchPhysicalDeletePersonExtSubmit(userDto.getProvince(), agencyIds,agencyVerify.getIsThirteen());
        //List<PersonExt> personExts=personExtDao.queryPersonExt(agencyIds);
        List<PersonExt> personHistory=personExtDao.queryPersonHistory(agencyIds);
        //List<SalaryMonthEndVO> salaryMonthEndVOList = salaryMonthEndDao.selectSalaryMonthEndWithSalaryType(userDto.getProvince(), agencyIds);
        List<SalaryMonthEndVO> salaryMonthMultipleEndVOList = agencySalaryMultipleDao.selectSalaryMonthEndWithSalaryType(userDto.getProvince(), agencyIds);



        try {
            salaryMonthEndSubmitDao.batchSaveSalaryMonthSubmit(salaryMonthMultipleEndVOList);
            personExtSubmitDao.batchSavePersonExtSubmit(personHistory,agencyVerify.getIsThirteen());
        } catch (Exception e) {
            logger.info("====上报保存上报数据发生异常======");
            e.printStackTrace();
            throw e;
        }
        agencyVerifyDao.updateAgencyState(agencyVerify,userDto.getProvince());

        // 单位上报录入流程
        logger.info("==== 工资编报送审工作流 Begin ====");
        iSalaryWorkFlowService.doSalaryFlowMultiple(userDto, wfActionDTO);
        logger.info("==== 工资编报送审工作流 End ====");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void rejectSubmitUnitSalaryReport(AgencyVerifyParamVo agencyVerifyParamVo, UserDTO userDto) {
        // 调用工作流
        logger.info("====工资编报撤销送审 Begin======");
        // 获取单位审核状态信息
       // AgencyVerify agencyVerify = agencyVerifyDao.getInfoByAgencyId(agencyVerifyParamVo.getAgencyId());
        AgencyVerify agencyVerify = agencyVerifyDao.getInfoByBizKey(agencyVerifyParamVo.getBizKey());
        WfActionDTO<AgencyVerify> wfActionDTO = new WfActionDTO();
        wfActionDTO.setMenuguid(agencyVerifyParamVo.getMenuid());
        wfActionDTO.setActionType(ActionTypeEnum.WF_RECALL.getActionTypeCode());
        wfActionDTO.setBizDatas(agencyVerify);
        wfActionDTO.setBizKeyName("bizKey");
        //判断是否含有已办
        List<String> statusList=new ArrayList<>();
        statusList.add("2");
        List<String> bizkeyList=new ArrayList<>();
        bizkeyList.add(agencyVerify.getBizKey());
        List<Map> maps=iSalaryWorkFlowService.queryWorkflowInfoDouble(userDto,wfActionDTO,statusList,bizkeyList);
        for(Map map:maps){
            if(StringUtils.isEmpty(map.get("status"))){
                throw new AppRuntimeException("已送审，无法撤销！");
            }
        }
        try {
            iSalaryWorkFlowService.doSalaryFlowMultiple(userDto, wfActionDTO);
        }catch (Exception e){
            throw new AppRuntimeException(e.getMessage());
        }
        logger.info("====工资编报撤销送审 End======");
        // 修改表状态为撤销送审
        LocalDateTime dateTime = LocalDateTime.now();
        String updateTime = dateTime.format(DTF);
        agencyVerify.setUpdateTime(updateTime);
        agencyVerify.setIsSubmitInAgency(Integer.parseInt(SystemDictConstant.REVOKE));
        agencyVerifyDao.updateAgencyState(agencyVerify,userDto.getProvince());
//        try {
//            iSalaryWorkFlowService.doSalaryFlow(userDto, wfActionDTO);
//        }catch (Exception e){
//            throw new AppRuntimeException(e.getMessage());
//        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void rejectSubmitUnitSalaryReportOne(AgencyVerifyParamVo agencyVerifyParamVo, UserDTO userDto) {
        // 调用工作流
        logger.info("====工资编报撤销送审 Begin======");
        // 获取单位审核状态信息
        AgencyVerify agencyVerify = agencyVerifyDao.getInfoByAgencyId(agencyVerifyParamVo.getAgencyId());
        WfActionDTO<AgencyVerify> wfActionDTO = new WfActionDTO();
        wfActionDTO.setMenuguid(agencyVerifyParamVo.getMenuid());
        wfActionDTO.setActionType(ActionTypeEnum.WF_RECALL.getActionTypeCode());
        wfActionDTO.setBizDatas(agencyVerify);
        wfActionDTO.setBizKeyName("bizKey");

        logger.info("====工资编报撤销送审 End======");
        // 修改表状态为撤销送审
        LocalDateTime dateTime = LocalDateTime.now();
        String updateTime = dateTime.format(DTF);
        agencyVerify.setUpdateTime(updateTime);
        agencyVerify.setSalaryVerifiedInAgencyCode(NO_AUDIT);
        agencyVerify.setIsSalarySubmit(SystemDictConstant.IS_FALSE);
        agencyVerify.setIsSubmitInAgency(Integer.parseInt(SystemDictConstant.REVOKE));
        agencyVerifyDao.updateAgencyState(agencyVerify,userDto.getProvince());
        List<String> agencyIds=new ArrayList<>();
        agencyIds.add(agencyVerifyParamVo.getAgencyId());
        //撤销时先清空该单位上报数据
        salaryMonthEndSubmitDao.batchPhysicalDeleteSalaryMonthSubmits(userDto.getProvince(), agencyIds,agencyVerify.getIsThirteen());
        personExtSubmitDao.batchPhysicalDeletePersonExtSubmit(userDto.getProvince(), agencyIds,agencyVerify.getIsThirteen());
        //获取已锁定指标
        List<Map<String,Object>> payLockMap=iPayMentLockDao.selectPayMentLock(agencyIds);
        //解冻指标
        if(!CollectionUtils.isEmpty(payLockMap)) {
            commonService.batchGocpurbudgetThaw(payLockMap, userDto.getProvince(), userDto.getYear() + "", null);
            //清楚指标锁定表该单位的锁定信息
//            iPayMentLockDao.batchPhysicalDeletePayMentLock(agencyIds);
        }
        iSalaryWorkFlowService.doSalaryFlowMultiple(userDto, wfActionDTO);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String,Object> auditUnitAuditInCommit(List<String> agencyids,AgencyVerifyParamVo agencyVerifyParamVo, UserDTO userDto ,boolean is_one,String tokenid){
         String ERROR_RSCODE = "140999";
         String success="100000";
        boolean flag=true;
        //是否校验月份，预警月份为0时该值为false
        String months="0";
        //预警月份大与1的校验结果
        boolean monthflag=true;
        Map<String,Object> remap=new HashMap<>();
        AgencyInfo agency=agencyInfoService.getNameById(agencyVerifyParamVo.getAgencyId());
//        if("".equals(agency.getIsPaymentAgency()) || null==agency.getIsPaymentAgency()){
//            remap.put(ERROR_RSCODE, "请选择是否生成支付！");
//            return remap;
//        }
        if(!"0".equals(agency.getIsPaymentAgency())) {//判断是否是实拨单位，实拨单位冻结指标 0为实拨单位
            try {
                remap = iGenerateSalaryDataService.isPaymentEnough(agencyids, userDto,tokenid);//校验指标是否满足工资发放
                flag = "true".equals(remap.get("isEnough"));
                //是否校验月份，预警月份为0时该值为false
                months = remap.get("months").toString();
                //预警月份大与1的校验结果
                monthflag = "true".equals(remap.get("isMonthsEnough"));
            } catch (Exception e) {
                logger.info("送审异常",e);
                remap.put(ERROR_RSCODE, e.getMessage());
                return remap;
            }
        }else{
            flag=true;
            months="0";
        }
        if(flag){
        StringBuffer res=new StringBuffer();
        try {
            if(is_one) {//是否单岗上报
                submitUnitSalaryReportOne(agencyVerifyParamVo, userDto);//单岗上报走这个方法
            }else{
                auditUnitAudit(agencyVerifyParamVo, userDto);//审核通过，并上报
            }
        }catch (Exception e){//审核报错时解冻指标用
//            if("100000".equals(remap.get("rscode"))) {
//                commonService.batchGocpurbudgetThaw((List<Map<String, Object>>) remap.get("payList"), userDto.getProvince(), userDto.getYear() + "", null);
//            }
            remap.put(ERROR_RSCODE, e);
        }

        res.append("审核并上报成功！");
        if(!"0".equals(months)&&!"1".equals(months)&&!monthflag){
            res.append("但工资指标不足已发放").append(months).append("个月");
            commonService.pushMessageToApaas(userDto,agencyVerifyParamVo.getAgencyId(),
                    agency.getAgencyCode()+"-"+agency.getAgencyName()+"工资指标余额不够发放"+months+"个月");
            }
                remap.put(success,res.toString());
        }else{
                    commonService.pushMessageToApaas(userDto,agencyVerifyParamVo.getAgencyId(),
                    agency.getAgencyCode()+"-"+agency.getAgencyName()+"工资指标余额不足");
                remap.put(ERROR_RSCODE, "指标余额不足！");

        }
        return remap;
    }
    @Override
    public void auditUnitAudit(AgencyVerifyParamVo agencyVerifyParamVo, UserDTO userDto) throws Exception {
        AgencyVerify agencyVerify = agencyVerifyDao.getInfoByAgencyIds(agencyVerifyParamVo.getAgencyId());
        logger.info("====单位审核送审工作流 Begin ====");
        WfActionDTO<AgencyVerify> wfActionDTO = new WfActionDTO();
        wfActionDTO.setMenuguid(agencyVerifyParamVo.getMenuid());
        wfActionDTO.setActionType(ActionTypeEnum.WF_AUDIT.getActionTypeCode());
        wfActionDTO.setBizDatas(agencyVerify);
        wfActionDTO.setBizKeyName("bizKey");
        logger.info("====单位审核送审工作流 End ====");
        // 修改表状态
        LocalDateTime dateTime = LocalDateTime.now();
        String updateTime = dateTime.format(DTF);
        agencyVerify.setUpdateTime(updateTime);
        //agencyVerify.setIsSalarySubmit(Integer.parseInt(SystemDictConstant.NO_SUBMIT));
        agencyVerify.setSalaryVerifiedInAgencyCode(IS_AUDIT);
        // 审核完成直接上报
        agencyVerify.setIsSalarySubmit(SystemDictConstant.IS_TRUE);

        List<String> agencyIds=new ArrayList<>();
        agencyIds.add(agencyVerifyParamVo.getAgencyId());
        //上报时先清空该单位上报数据
        salaryMonthEndSubmitDao.batchPhysicalDeleteSalaryMonthSubmits(userDto.getProvince(), agencyIds,agencyVerify.getIsThirteen());
        personExtSubmitDao.batchPhysicalDeletePersonExtSubmit(userDto.getProvince(), agencyIds,agencyVerify.getIsThirteen());
       // List<PersonExt> personExts=personExtDao.queryPersonExt(agencyIds);
        List<PersonExt> personHistory=personExtDao.queryPersonHistory(agencyIds);
        // List<SalaryMonthEndVO> salaryMonthEndVOList = salaryMonthEndDao.selectSalaryMonthEndWithSalaryType(userDto.getProvince(), agencyIds);
        List<SalaryMonthEndVO> salaryMonthMultipleEndVOList = agencySalaryMultipleDao.selectSalaryMonthEndWithSalaryType(userDto.getProvince(), agencyIds);
        try {

            salaryMonthEndSubmitDao.batchSaveSalaryMonthSubmit(salaryMonthMultipleEndVOList);
            personExtSubmitDao.batchSavePersonExtSubmit(personHistory,agencyVerify.getIsThirteen());
        } catch (NoSuchMethodException e) {
            logger.info("====上报保存上报数据发生异常======");
            e.printStackTrace();
            throw e;
        } catch (InvocationTargetException e) {
            logger.info("====上报保存上报数据发生异常======");
            e.printStackTrace();
            throw e;
        } catch (IllegalAccessException e) {
            logger.info("====上报保存上报数据发生异常======");
            e.printStackTrace();
            throw e;
        }
        agencyVerifyDao.updateAgencyState(agencyVerify,userDto.getProvince());
        iSalaryWorkFlowService.doSalaryFlowMultiple(userDto, wfActionDTO);


    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void auditUnitAuditMiddle(AgencyVerifyParamVo agencyVerifyParamVo, UserDTO userDto) {
        AgencyVerify agencyVerify = agencyVerifyDao.getInfoByAgencyId(agencyVerifyParamVo.getAgencyId());
        WfActionDTO<AgencyVerify> wfActionDTO = new WfActionDTO();
        wfActionDTO.setMenuguid(agencyVerifyParamVo.getMenuid());
        wfActionDTO.setActionType(ActionTypeEnum.WF_AUDIT.getActionTypeCode());
        wfActionDTO.setBizDatas(agencyVerify);
        wfActionDTO.setBizKeyName("bizKey");
        logger.info("====单位审核送审工作流 Begin ====");
        iSalaryWorkFlowService.doSalaryFlowMultiple(userDto, wfActionDTO);
        logger.info("====单位审核送审工作流 End ====");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void rejectAuditUnitAudit(AgencyVerifyParamVo agencyVerifyParamVo, UserDTO userDto) throws AppRuntimeException {
        // 获取单位审核状态信息
        AgencyVerify agencyVerify = agencyVerifyDao.getInfoByBizKey(agencyVerifyParamVo.getBizKey());
        logger.info("====单位审核撤销审核工作流 Begin ====");
        WfActionDTO<AgencyVerify> wfActionDTO = new WfActionDTO();
        wfActionDTO.setMenuguid(agencyVerifyParamVo.getMenuid());
        // 撤销上报
        wfActionDTO.setActionType(ActionTypeEnum.WF_RECALL.getActionTypeCode());
        wfActionDTO.setBizDatas(agencyVerify);
        wfActionDTO.setBizKeyName("bizKey");
        wfActionDTO.setMessage(agencyVerifyParamVo.getAuditExplain());
        //判断是否含有已办
        List<String> statusList=new ArrayList<>();
        statusList.add("2");
        List<String> bizkeyList=new ArrayList<>();
        bizkeyList.add(agencyVerify.getBizKey());
        List<Map> maps=iSalaryWorkFlowService.queryWorkflowInfoDouble(userDto,wfActionDTO,statusList,bizkeyList);
        for(Map map:maps){
            if(StringUtils.isEmpty(map.get("status"))){
                throw new AppRuntimeException("财政已接收，无法撤销！");
            }
        }


        logger.info("====单位审核撤销审核工作流 End======");
        LocalDateTime dateTime = LocalDateTime.now();
        String updateTime = dateTime.format(DTF);
        agencyVerify.setUpdateTime(updateTime);
        agencyVerify.setSalaryVerifiedInAgencyCode(NO_AUDIT);
        agencyVerify.setIsSalarySubmit(0);//撤销时修改上报状态为未上报
        agencyVerifyDao.updateAgencyState(agencyVerify,userDto.getProvince());

        List<String> agencyIds=new ArrayList<>();
        agencyIds.add(agencyVerifyParamVo.getAgencyId());
        //撤销时先清空该单位上报数据
        salaryMonthEndSubmitDao.batchPhysicalDeleteSalaryMonthSubmits(userDto.getProvince(), agencyIds,agencyVerify.getIsThirteen());
        personExtSubmitDao.batchPhysicalDeletePersonExtSubmit(userDto.getProvince(), agencyIds,agencyVerify.getIsThirteen());
        //获取已锁定指标
        List<Map<String,Object>> payLockMap=iPayMentLockDao.selectPayMentLock(agencyIds);
        //解冻指标
        if(!CollectionUtils.isEmpty(payLockMap)) {
            commonService.batchGocpurbudgetThaw(payLockMap, userDto.getProvince(), userDto.getYear() + "", null);
//            //清楚指标锁定表该单位的锁定信息
//            iPayMentLockDao.batchPhysicalDeletePayMentLock(agencyIds);
        }
        try {
            iSalaryWorkFlowService.doSalaryFlowMultiple(userDto, wfActionDTO);
        }catch (Exception e){
            throw new AppRuntimeException(e.getMessage());
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void rejectAuditUnitAuditMiddle(AgencyVerifyParamVo agencyVerifyParamVo, UserDTO userDto) throws AppRuntimeException {
        // 获取单位审核状态信息
        AgencyVerify agencyVerify = agencyVerifyDao.getInfoByAgencyId(agencyVerifyParamVo.getAgencyId());
        logger.info("====单位审核撤销审核工作流 Begin ====");
        WfActionDTO<AgencyVerify> wfActionDTO = new WfActionDTO();
        wfActionDTO.setMenuguid(agencyVerifyParamVo.getMenuid());
        // 撤销上报
        wfActionDTO.setActionType(ActionTypeEnum.WF_RECALL.getActionTypeCode());
        wfActionDTO.setBizDatas(agencyVerify);
        wfActionDTO.setBizKeyName("bizKey");
        wfActionDTO.setMessage(agencyVerifyParamVo.getAuditExplain());
        //判断是否含有已办
        List<String> statusList=new ArrayList<>();
        statusList.add("2");
        List<String> bizkeyList=new ArrayList<>();
        bizkeyList.add(agencyVerify.getBizKey());
        List<Map> maps=iSalaryWorkFlowService.queryWorkflowInfoStatus(userDto,wfActionDTO,statusList,bizkeyList);
        for(Map map:maps){
            if(StringUtils.isEmpty(map.get("status"))){
                throw new AppRuntimeException("下一岗已处理，无法撤销！");
            }
        }
        try {
            iSalaryWorkFlowService.doSalaryFlowMultiple(userDto, wfActionDTO);
        }catch (Exception e){
            throw new AppRuntimeException(e.getMessage());
        }

        logger.info("====单位审核撤销审核工作流 End======");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void returnedUnitAudit(AgencyVerifyParamVo agencyVerifyParamVo, UserDTO userDto) {
        // 获取单位审核状态信息
        List<AgencyVerify> agencyVerifyList = agencyVerifyDao.getInfoByAgency(agencyVerifyParamVo.getAgencyId());
        List<AgencyVerify>agencyVerifyDoubleList=new ArrayList<>();
        for(AgencyVerify agencyVerify: agencyVerifyList){
            if(agencyVerify.getIsThirteen()>0){
                agencyVerifyDoubleList.add(agencyVerify);
            }
        }
        if(agencyVerifyDoubleList.size()>0){
            for(AgencyVerify agencyVerify:agencyVerifyDoubleList){
                logger.info("====单位审核退回工作流 Begin ====");
                WfActionDTO<AgencyVerify> wfActionDTO = new WfActionDTO();
                wfActionDTO.setMenuguid(agencyVerifyParamVo.getMenuid());
                wfActionDTO.setActionType(ActionTypeEnum.WF_BACK.getActionTypeCode());
                wfActionDTO.setBizDatas(agencyVerify);
                wfActionDTO.setBizKeyName("bizKey");
                wfActionDTO.setMessage(agencyVerifyParamVo.getAuditExplain());
                LocalDateTime dateTime = LocalDateTime.now();
                String updateTime = dateTime.format(DTF);
                agencyVerify.setUpdateTime(updateTime);
                agencyVerify.setIsSubmitInAgency(Integer.parseInt(SystemDictConstant.IS_REJECT));
                agencyVerify.setSalaryVerifiedInAgencyCode(SystemDictConstant.IS_REJECT);
                agencyVerifyDao.updateAgencyState(agencyVerify,userDto.getProvince());
                iSalaryWorkFlowService.doSalaryFlowMultiple(userDto, wfActionDTO);
                logger.info("==== 单位审核退回工作流 End  ===");
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void rejectReturnedUnitAudit(String agencyId,UserDTO userDto) {
        LocalDateTime dateTime = LocalDateTime.now();
        String updateTime = dateTime.format(DTF);
        AgencyVerify agencyVerify = new AgencyVerify();
        agencyVerify.setAgencyId(agencyId);
        agencyVerify.setUpdateTime(updateTime);
        agencyVerify.setIsSubmitInAgency(Integer.parseInt(SystemDictConstant.IS_SUBMIT));
        agencyVerifyDao.updateAgencyState(agencyVerify,userDto.getProvince());
    }

    @Override
    public boolean getReturnedState(String agencyId) {
        Map<String, Object> returnedStateMap = agencyVerifyDao.selectStateByAgencyId(agencyId,"0", "is_submit_in_agency");
        return SystemDictConstant.IS_REJECT.equals(returnedStateMap.get("is_submit_in_agency").toString());
    }

    @Override
    public Map<String, String> getReallySendSalarySumAndPersonTotal(String agencyId, String isThirteen, String salaryType) {
        Map<String, String> result = new HashMap<>();
//        查询在册人数，在职人数，离休人数
        UnitSalaryReportVO UnitSalaryReportVO = personInfoDao.selectSendSalaryPersonTotal(agencyId, salaryType);
        result.put("personTotal",String.valueOf(UnitSalaryReportVO.getPersonTotal()));
        result.put("workTotal",String.valueOf(UnitSalaryReportVO.getWorkTotal()));
        result.put("retireTotal",String.valueOf(UnitSalaryReportVO.getRetireTotal()));
//        查询单位减员和单位增员
        Map<String,Object> stateMap = agencyVerifyDao.selectStateByAgencyId(agencyId,isThirteen, "salary_month");
        String salaryMonth = String.valueOf(stateMap.get("salary_month"));
        UnitSalaryReportVO unitSalaryReportVO1 = personOperateDao.selectPersonPlusAndMinusCount(agencyId, salaryMonth);
        result.put("unitPlusTotal",String.valueOf(unitSalaryReportVO1.getUnitPlusTotal()));
        result.put("unitMinusTotal",String.valueOf(unitSalaryReportVO1.getUnitMinusTotal()));
        //查询增员减员（在职、离休）
        UnitSalaryReportVO unitSalaryReportVO3 = personOperateDao.selectPersonMinusAndPlus(agencyId, salaryMonth);
        result.put("retireMinusTotal",String.valueOf(unitSalaryReportVO3.getRetireMinusTotal()));
        result.put("workMinusTotal",String.valueOf(unitSalaryReportVO3.getWorkMinusTotal()));
        result.put("retirePlusTotal",String.valueOf(unitSalaryReportVO3.getRetirePlusTotal()));
        result.put("workPlusTotal",String.valueOf(unitSalaryReportVO3.getWorkPlusTotal()));
        Map<String, Object> queryParam=new HashMap<>();
        queryParam.put("agencyId", agencyId);
        int total = personOperateDao.getPersonChangeTotal(queryParam);
        result.put("personUpdateTotal",String.valueOf(total));
//查询实发工资字段名（目前已定死为s1）
//        String columnName = agencySalaryDao.selectReallySendSalaryColumnName(agencyId);
//        if(StringUtils.isEmpty(columnName)){
//            //如果columnName为null，表示当前机构没有绑定实发工资项，默认返回零
//            result.put("reallySendSalarySum", "0.00");
//            result.put("workSalarySum", "0.00");
//            result.put("retireSalarySum", "0.00");
//        }else{
           // UnitSalaryReportVO unitSalaryReportVO2 = salaryMonthEndDao.selectReallySendSalarySum(agencyId, queryThirteen, "s1", salaryType);
            UnitSalaryReportVO unitSalaryReportVO2 = agencySalaryMultipleDao.selectReallySendSalarySum(agencyId, isThirteen, "s1", salaryType);
            result.put("reallySendSalarySum",String.valueOf(unitSalaryReportVO2.getReallySendSalarySum()));
            result.put("workSalarySum", String.valueOf(unitSalaryReportVO2.getWorkSalarySum()));
            result.put("retireSalarySum", String.valueOf(unitSalaryReportVO2.getRetireSalarySum()));
       // }
        return result;
    }
    /**
     *获取上报实发工资总和和机构总人数
     */
    @Override
    public Map<String, String> querySubmitReallySendSalarySumAndPersonTotal(String agencyId,String isThirteen, Integer queryThirteen, String salaryType) {
        Map<String, String> result = new HashMap<>();
//        查询在册人数，在职人数，离休人数
        UnitSalaryReportVO UnitSalaryReportVO = personInfoDao.selectSubmitSendSalaryPersonTotal(agencyId,isThirteen, salaryType);
        //在编人员
        result.put("personTotal",String.valueOf(UnitSalaryReportVO.getPersonTotal()));
        //在编人员中在职人员
        result.put("workTotal",String.valueOf(UnitSalaryReportVO.getWorkTotal()));
        //在编人员中离休人员
        result.put("retireTotal",String.valueOf(UnitSalaryReportVO.getRetireTotal()));
//        查询单位减员和单位增员
        Map<String,Object> stateMap = agencyVerifyDao.selectStateByAgencyId(agencyId,isThirteen, "salary_month","is_auto");
        String salaryMonth = String.valueOf(stateMap.get("salary_month"));
        //salaryMonth:统发月份  is_auto:自动上报
        result.put("salaryMonth",salaryMonth);
        String isauto = String.valueOf(stateMap.get("is_auto"));
        UnitSalaryReportVO unitSalaryReportVO1 = personOperateDao.selectPersonPlusAndMinusCount(agencyId, salaryMonth);
        //单位增员
        result.put("unitPlusTotal",SystemDictConstant.IS_SUBMIT.equals(isauto)?"0":String.valueOf(unitSalaryReportVO1.getUnitPlusTotal()));
        //单位减员
        result.put("unitMinusTotal",SystemDictConstant.IS_SUBMIT.equals(isauto)?"0":String.valueOf(unitSalaryReportVO1.getUnitMinusTotal()));
        //查询增员减员（在职、离休）若是自动上报默认月初数据所有变化为0
        UnitSalaryReportVO unitSalaryReportVO3 = personOperateDao.selectPersonMinusAndPlus(agencyId, salaryMonth);
        //单位减员中离休人员
        result.put("retireMinusTotal",SystemDictConstant.IS_SUBMIT.equals(isauto)?"0":String.valueOf(unitSalaryReportVO3.getRetireMinusTotal()));
        //单位减员中在职人员
        result.put("workMinusTotal",SystemDictConstant.IS_SUBMIT.equals(isauto)?"0":String.valueOf(unitSalaryReportVO3.getWorkMinusTotal()));
        //单位增员中离休人员
        result.put("retirePlusTotal",SystemDictConstant.IS_SUBMIT.equals(isauto)?"0":String.valueOf(unitSalaryReportVO3.getRetirePlusTotal()));
        //单位增员中在职人员
        result.put("workPlusTotal",SystemDictConstant.IS_SUBMIT.equals(isauto)?"0":String.valueOf(unitSalaryReportVO3.getWorkPlusTotal()));
        Map<String, Object> queryParam=new HashMap<>();
        queryParam.put("agencyId", agencyId);
        int total = personOperateDao.getPersonChangeTotal(queryParam);
        //人事变动
        result.put("personUpdateTotal",SystemDictConstant.IS_SUBMIT.equals(isauto)?"0":String.valueOf(total));
//查询实发工资字段名（目前已定死为s1）
        String columnName = "s1";//agencySalaryDao.selectReallySendSalaryColumnName(agencyId);
        String columnName2 = "s2";
        if(StringUtils.isEmpty(columnName)){
            //如果columnName为null，表示当前机构没有绑定实发工资项，默认返回零
            result.put("reallySendSalarySum", "0.00");
            result.put("reallySendChangeSum", "0.00");
            result.put("workSalarySum", "0.00");
            result.put("retireSalarySum", "0.00");
        }else{
            UnitSalaryReportVO unitSalaryReportVO2 = salaryMonthEndDao.selectSubmitReallySendSalarySum(agencyId,isThirteen, queryThirteen, columnName, salaryType);
            //将在编实发合计转换成BigDecimal类型
            BigDecimal bigReallySendSalarySum = new BigDecimal(unitSalaryReportVO2.getReallySendSalarySum());
            //获取月初实发总和，返回值Double类型，将其转换成BigDecimal类型
            BigDecimal monthReallySendSum = new BigDecimal(salaryMonthEndDao.selectSubmitReallySendChangeSum(agencyId,columnName));
            //运算实发变动合计
            //BigDecimal bigReallySendChangeSum = bigReallySendSalarySum.subtract(monthReallySendSum);

            //在编实发合计
            result.put("reallySendSalarySum",String.valueOf(unitSalaryReportVO2.getReallySendSalarySum()));
            //实发变动合计
            //保留两位小数：bigReallySendChangeSum.setScale(2,BigDecimal.ROUND_HALF_UP)
            result.put("reallySendChangeSum",String.valueOf(bigReallySendSalarySum.subtract(monthReallySendSum)));
            //在编实发合计中在职合计
            result.put("workSalarySum", String.valueOf(unitSalaryReportVO2.getWorkSalarySum()));
            //在编实发合计中离休合计
            result.put("retireSalarySum", String.valueOf(unitSalaryReportVO2.getRetireSalarySum()));
        }

        if(StringUtils.isEmpty(columnName2)){
            //如果columnName为null，表示当前机构没有绑定实发工资项，默认返回零
            result.put("shouldSend", "0.00");
        }else{
            UnitSalaryReportVO unitSalaryReportVO2 = salaryMonthEndDao.selectSubmitReallySendSalarySum(agencyId,isThirteen
                    , queryThirteen, columnName2, salaryType);
            BigDecimal bigReallySendSalarySum = new BigDecimal(unitSalaryReportVO2.getReallySendSalarySum());
            BigDecimal shouldSend= new BigDecimal(salaryMonthEndDao.selectSubmitReallyShouldSendSum(agencyId,columnName2));
            result.put("shouldSendChangeSum",String.valueOf(bigReallySendSalarySum.subtract(shouldSend)));
        }
        return result;
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<Map<String, Object>> getPersonSalaryInfo(String agencyId,String personId,List<String> personTypes,String mof_div_code) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        // 获取单位下挂接的工资项
        List<PersonTypeSalary> list=iPersonTypeSalaryDao.getInfoByPersonTypes4Unit(personTypes,mof_div_code);
       // List<AgencySalaryVO> list = agencySalaryDao.selectColumnName(agencyId);
        // 获取人员下工资项的值
        if (list.size() > 0) {
            clazz = null;
            methods = null;
            List<String> column_name = list.stream().map(PersonTypeSalary::getColumnName).collect(Collectors.toList());
            List<SalaryMonthEnd> salaryList = agencySalaryMultipleDao.getSalaryMonthByPersonId(column_name, agencyId, personId);
            //List<SalaryMonthEnd> salaryList = agencySalaryDao.getSalaryMonthEedSubmitByPersonId(column_name, agencyId, personId);
            if (list.size() > 0) {
                for (PersonTypeSalary personTypeSalary : list) {
                    Map<String, Object> map = new HashMap<>(3);

                    map.put("keyId", personTypeSalary.getSalaryId());//工资项表id
                    map.put("name", personTypeSalary.getSalaryName() + "：");//工资项名称
                    map.put("columnName",personTypeSalary.getColumnName());//工资项对应工资表字段
                    map.put("isCompute",personTypeSalary.getIsCompute());//计算项对应工资表字段
                    map.put("isStandard",personTypeSalary.getIsStandard()==null?0:personTypeSalary.getIsStandard());//是否标准对应工资表字段
                    map.put("isShow",personTypeSalary.getIsShow()==null?1:personTypeSalary.getIsShow());//是否标准对应工资表字段
                    if(salaryList.size()>0) {
                        map.put("id",salaryList.get(0).getId());//工资表id
                        map.put("value", converBeanFiledForObject(salaryList.get(0), "getS" + personTypeSalary.getColumnName().replaceAll("s", "")));//工资金额
                    }else{
                        map.put("id",null);//工资表id
                        map.put("value",0);
                    }
                    resultList.add(map);
                }
            }
        }
        return resultList;
    }

    @Override
    public List<AgencySalaryVO> getColumnByAgencyId(UserDTO userDTO) {
        return agencySalaryMultipleDao.selectColumnName(userDTO);
    }

    @Override
    public List<AgencySalaryVO> getExccelColumnName(UserDTO userDTO) {
        return agencySalaryMultipleDao.selectColumnName(userDTO);
    }

    @Override
    public List<Map<String, Object>> getUnitSalaryReport(UserDTO userDTO,String agencyId, String flag, Map<String, Object>
            condition) throws AppRuntimeException {
        List<Map<String, Object>> result = Collections.emptyList();

//        查询当前月份，送审状态及工资变动状态
        Map<String,Object> stateMap = agencyVerifyDao.selectStateByAgencyId
                (agencyId,"0","salary_month","is_submit_in_agency");
//        当月月份
        String salaryMonth = String.valueOf(stateMap.get("salary_month"));
//        上月月份
        String lastSalaryMonth = LocalDate.parse(salaryMonth+"-01", DateTimeFormatter.ofPattern("yyyy-MM-dd"))
                .minusMonths(1).format(DateTimeFormatter.ofPattern("yyyy-MM"));
//        判断当前处于哪一个tab页

//        获取当月工资字段名
        List<AgencySalaryVO> currentcolumnList = agencySalaryMultipleDao.selectColumnName(userDTO);
        if(CollectionUtils.isEmpty(currentcolumnList)){
            throw new AppRuntimeException("当前机构未挂接工资项！");
        }
        List<String> salaryColumns = currentcolumnList.stream().map(AgencySalaryVO::getColumnName).collect
                (Collectors.toList());
        List<String> salaryIds = currentcolumnList.stream().map(AgencySalaryVO::getSalaryId).collect
                (Collectors.toList());
//        获取上月工资字段名
//        List<AgencySalaryVO> lastColumnList = agencySalaryDao.selectLastColumnName(agencyId, salaryIds,
//                lastSalaryMonth);
//获取当月salaryID对应字段名map
        Map<String,String> currentSalaryIdJoinColumnMap = currentcolumnList.stream()
                .collect(Collectors.toMap(AgencySalaryVO::getSalaryId, AgencySalaryVO::getColumnName));
//        获取上月salaryID对应字段名map
//        Map<String,String> lastSalaryIdJoinColumnMap = lastColumnList.stream()
//                .collect(Collectors.toMap(AgencySalaryVO::getSalaryId, AgencySalaryVO::getColumnName));
//查询编报数据
        List<Map<String, Object>> salaryMonthEndDatas = agencySalaryMultipleDao.getSelectUnitSalaryReport(agencyId,
                salaryIds, salaryMonth, lastSalaryMonth, currentSalaryIdJoinColumnMap, null, condition);
        if (!CollectionUtils.isEmpty(salaryMonthEndDatas)) {
            int[] index = {1};
            result = salaryMonthEndDatas.stream().peek(salaryMonthEndData -> {
                if(SystemDictConstant.IS_TRUE.toString().equals(String.valueOf(salaryMonthEndData.get
                        ("different")))){
                    Map<String,Object> salaryHistory = new HashMap<>(salaryMonthEndData);
                    salaryHistory.put("currentMonth", salaryHistory.get("currentMonth_history"));
                    for(String salaryId : salaryIds){
                        String columnName = currentSalaryIdJoinColumnMap.get(salaryId);
                        salaryHistory.put(columnName, salaryMonthEndData.get(columnName + "_history"));
                        salaryHistory.put(columnName + "_history", salaryMonthEndData.get(columnName));
                    }
                    salaryMonthEndData.put("children", Collections.singletonList(salaryHistory));
                }
                salaryMonthEndData.put("index",index[0]++);
            }).collect(Collectors.toList());

        }
        return result;
    }

    @Override
    public Map<String, Object> getSalaryState(String agencyId, String... columnNames) {
        //        查询当前月份，送审状态及工资变动状态
        Map<String,Object> stateMap = agencyVerifyDao.selectStateByAgencyId(agencyId,"0","salary_month","is_submit_in_agency");
        return stateMap;
    }

    @Override
    public boolean verfityExistNoFilePerson(String agencyId) {
//        查询当前月份，送审状态及工资变动状态
        Map<String,Object> stateMap = agencyVerifyDao.selectStateByAgencyId(agencyId,"0","salary_month");
//        当月月份
        String salaryMonth = String.valueOf(stateMap.get("salary_month"));

//        查询工资有变动的人员id
        //List<String> personIdList = salaryMonthEndDao.selectDifferentPersonId(agencyId);
        List<String> personIdList = agencySalaryMultipleDao.selectDifferentPersonId(agencyId);
        List<String> changePersonIdList=personOperateDao.selectChangePersonByAgencyMonth(agencyId,salaryMonth);
        if(!CollectionUtils.isEmpty(personIdList)||!CollectionUtils.isEmpty(changePersonIdList)){
//        查询工资有变动且已经上传附件的人员数量
            int count = fileInfoDao.selectHaveFilePersonCount(agencyId, salaryMonth, personIdList);
            int changecount = fileInfoDao.selectHaveFilePersonCount(agencyId, salaryMonth, changePersonIdList);
//            工资变动人员数量是否大于上传附件人员数量
            return personIdList.size() > count||changePersonIdList.size()> changecount;
        }else{
            return false;
        }
    }


    /**
     * 获取数组中连续数字的缺失值，如果 不存在，返回最大值+1
     *
     * @param array
     * @return
     */
    private Integer getNumber(List<Integer> array) {
        int defetNum = 0;
        Hashtable<Integer, Integer> hasht = new Hashtable<Integer, Integer>();
        for (int i = 0; i < array.size(); i++) {
            hasht.put(array.get(i), 1);
        }
        for (int i = 1; i <= array.size() - 1; i++) {
            if (hasht.get(i) == null) {
                defetNum = i;
                break;
            }
        }
        if (defetNum == 0) {
            defetNum = getMaxNum(array) + 1;
        }
        return defetNum;
    }

    /**
     * 获取数组中的最大值
     *
     * @param array
     * @return
     */
    public Integer getMaxNum(List<Integer> array) {
        // 定义一个参照物
        int max = array.get(0);
        //遍历数组
        for (int i = 0; i < array.size(); i++) {
            //判断大小
            if (array.get(i) > max) {
                max = array.get(i);
            }
        }
        return max;
    }

    /**
     * 通过反射类，获取字段值
     * @param bean
     * @param column
     * @param <T>
     * @return
     */
    private <T> Object converBeanFiledForObject(T bean, String column) {
        Object object = null;
        if (clazz != null && methods != null) {
            for (Method method: methods) {
                if (column.equals(method.getName())) {
                    try {
                        object = method.invoke(bean);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }
                    break;
                }
            }
        } else {
            clazz = bean.getClass();
            methods = clazz.getDeclaredMethods();
            if (methods.length > 0) {
                for (Method method: methods) {
                    if (column.equals(method.getName())) {
                        try {
                            object = method.invoke(bean);
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        } catch (InvocationTargetException e) {
                            e.printStackTrace();
                        }
                        break;
                    }
                }
            }
        }
        return object;
    }

    @Override
    public PageDTO<Map<String, Object>> getFinancialAuditSalaryPage(PaginationDTO paginationDTO,
                                                         String agencyId,
                                                         String flag,
                                                         Map<String, Object> condition,String mofDivCode) throws AppRuntimeException {
        List<Map<String, Object>> result = Collections.emptyList();
        PageDTO<Map<String, Object>> pageDTO = new PageDTO<>();
        pageDTO.setRows(result);
        pageDTO.setTotal(0);
        logger.info("======审核查询明细数据单位状态Start"+  DateUtils.getCurrentTimeStamp());
        Map<String,Object> stateMap = agencyVerifyDao.selectStateByAgencyId(agencyId,"0",
                "salary_month","is_submit_in_agency","salary_verified_in_agency_code","is_salary_change","is_salary_submit");
        logger.info("======审核查询明细数据单位状态end"+  DateUtils.getCurrentTimeStamp());
        String salaryMonth = String.valueOf(stateMap.get("salary_month"));
//        上月月份
        String lastSalaryMonth = LocalDate.parse(salaryMonth+"-01", DateTimeFormatter.ofPattern("yyyy-MM-dd"))
                .minusMonths(1).format(DateTimeFormatter.ofPattern("yyyy-MM"));
//当前机构工资变动状态

        int isSalaryChange = Integer.parseInt(String.valueOf(stateMap.get("is_salary_change")));
        // 如果单位送审状态是未送审、被退回、撤销时，直接返回
        String submitState = stateMap.get("is_submit_in_agency").toString();
        //上报状态
        String submitUpState = stateMap.get("is_salary_submit").toString();

        if(SystemDictConstant.NO_SUBMIT.equals(submitState) || SystemDictConstant.IS_REJECT.equals(submitState) || SystemDictConstant.REVOKE.equals(submitState)){
            return pageDTO;
        }
//        判断当前处于哪一个tab页
        if(!"all".equals(flag)){
            //单位审核状态
            String auditState = stateMap.get("salary_verified_in_agency_code").toString();

            if (SystemDictConstant.NO_SUBMIT.equals(flag)) {
                if (!SystemDictConstant.NO_SUBMIT.equals(auditState) && !SystemDictConstant.IS_REJECT.equals(auditState)) {
                    return pageDTO;
                }
            } else if (SystemDictConstant.IS_SUBMIT.equals(flag)){
                if(!SystemDictConstant.IS_SUBMIT.equals(auditState)){
                    return pageDTO;
                }
            }else if(!submitUpState.equals(flag)){
                return pageDTO;
            }
        }




//        获取当月工资字段名
        List<String> personTypes=new ArrayList<>();
//        获取当月工资字段名
        Object salaryType = condition.get("salaryType");
        if (!StringUtils.isEmpty(salaryType)) {
            personTypes.add(salaryType.toString());
        }else {
            logger.info("======审核查询明细数据人员类型Start"+  DateUtils.getCurrentTimeStamp());
            personTypes = iPersonTypeSalaryDao.getAllPersonTypeByAgencyId(agencyId);
            logger.info("======审核查询明细数据人员类型end"+  DateUtils.getCurrentTimeStamp());
        }
        logger.info("======审核查询明细数据工资项Start"+  DateUtils.getCurrentTimeStamp());
        List<PersonTypeSalary> currentcolumnList=iPersonTypeSalaryDao.getInfoByPersonTypes4Unit(personTypes,mofDivCode);
        logger.info("======审核查询明细数据工资项end"+  DateUtils.getCurrentTimeStamp());
        // List<AgencySalaryVO> currentcolumnList = agencySalaryDao.selectColumnName(agencyId);
        if(CollectionUtils.isEmpty(currentcolumnList)){
            throw new AppRuntimeException("当前机构未挂接工资项！");
        }
        List<String> salaryColumns = currentcolumnList.stream().map(PersonTypeSalary::getColumnName).collect(Collectors.toList());
        List<String> salaryIds = currentcolumnList.stream().map(PersonTypeSalary::getSalaryId).collect(Collectors.toList());
//        获取上月工资字段名
        // List<AgencySalaryVO> lastColumnList = agencySalaryDao.selectLastColumnName(agencyId, salaryIds, lastSalaryMonth);
//获取当月salaryID对应字段名map
        Map<String,String> currentSalaryIdJoinColumnMap = currentcolumnList.stream()
                .collect(Collectors.toMap(PersonTypeSalary::getSalaryId, PersonTypeSalary::getColumnName));
//        获取上月salaryID对应字段名map
        // Map<String,String> lastSalaryIdJoinColumnMap = lastColumnList.stream()
        // .collect(Collectors.toMap(AgencySalaryVO::getSalaryId, AgencySalaryVO::getColumnName));
//查询上报数据
        logger.info("======审核查询明细数据工资Start"+  DateUtils.getCurrentTimeStamp());
        List<Map<String, Object>> salaryMonthEndDatas = agencySalaryMultipleDao.getFinancialAuditSalaryPage(
                paginationDTO, agencyId, salaryIds, salaryMonth, lastSalaryMonth, currentSalaryIdJoinColumnMap,  condition,mofDivCode);
        logger.info("======审核查询明细数据工资end"+  DateUtils.getCurrentTimeStamp());
        if (!CollectionUtils.isEmpty(salaryMonthEndDatas)) {
            int[] index = {1};
//            获取当前机构的工资变动状态
            int[] different = {0};
            result = salaryMonthEndDatas.stream().peek(salaryMonthEndData -> {
//                工资照比上个月有变动
                if(SystemDictConstant.IS_TRUE.toString().equals(String.valueOf(salaryMonthEndData.get("different")))){
                    Map<String,Object> salaryHistory = new HashMap<>(salaryMonthEndData);
                    salaryHistory.put("currentMonth", salaryHistory.get("currentMonth_history"));
                    for(String salaryId : salaryIds){
                        String columnName = currentSalaryIdJoinColumnMap.get(salaryId);
                        salaryHistory.put(columnName, salaryMonthEndData.get(columnName + "_history"));
                        salaryHistory.put(columnName + "_history", salaryMonthEndData.get(columnName));
                    }
                    salaryMonthEndData.put("children", Collections.singletonList(salaryHistory));
                    different[0] = 1;
                }
                salaryMonthEndData.put("index",index[0]++);
            }).collect(Collectors.toList());
            logger.info("======审核查询明细数据总条数Start"+  DateUtils.getCurrentTimeStamp());
            int total = agencySalaryMultipleDao.selectFinancialAuditSalaryTotal(agencyId, lastSalaryMonth, condition,mofDivCode);
            logger.info("======审核查询明细数据总条数end"+  DateUtils.getCurrentTimeStamp());
//计算上报的各个工资项合计值
            logger.info("======审核查询明细数据合计start"+  DateUtils.getCurrentTimeStamp());
            Map<String, Object> salaryMonthEndSum = agencySalaryMultipleDao.selectSalaryMonthEndSubmSum(
                    agencyId, SystemDictConstant.IS_TRUE, salaryColumns, condition,mofDivCode);
            logger.info("======审核查询明细数据合计end"+  DateUtils.getCurrentTimeStamp());
            salaryMonthEndSum.put("index", "合计");
            result.add(0, salaryMonthEndSum);
//            设置返回值
            pageDTO.setRows(result);
            pageDTO.setTotal(total);
//            判断机构的工资变动状态是否改变，改变则更新状态到agency_salary表
           /* if (isSalaryChange <= 0) {
                if(paginationDTO.getCurrpage() == 1 && different[0] != isSalaryChange){
                    AgencyVerify agencyVerify = new AgencyVerify();
                    agencyVerify.setAgencyId(agencyId);
                    agencyVerify.setUpdateTime(String.valueOf(DateUtils.getCurrentTimeStamp()));
                    agencyVerify.setIsSalaryChange(different[0]);
                    agencyVerifyDao.updateAgencyState(agencyVerify);
                }
            }*/
        }
        return pageDTO;
    }



    /**
     *通过单位ID查询PersonExt表银行信息
     * @param agencyId
     * @return List<PersonExt>
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<PersonExt> selectPersonExtByAgencyId (String agencyId){
        return agencyVerifyDao.selectPersonExtByAgencyId(agencyId);
    }

    /**
     *通过单位ID查询AgencyExt表银行信息
     * @param agencyId
     * @return AgencyExt
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AgencyExt selectAgencyExtByAgencyId(String agencyId) {
        return agencyVerifyDao.selectAgencyExtByAgencyId(agencyId);
    }

    @Override
    public List<Map<String, Object>> getSalaryMonthEedSubmit(String agencyId, String personId, List<String> personTypes, String mof_div_code) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        // 获取单位下挂接的工资项
        List<PersonTypeSalary> list=iPersonTypeSalaryDao.getInfoByPersonTypes4Unit(personTypes,mof_div_code);
        // List<AgencySalaryVO> list = agencySalaryDao.selectColumnName(agencyId);
        // 获取人员下工资项的值
        if (list.size() > 0) {
            clazz = null;
            methods = null;
            List<String> column_name = list.stream().map(PersonTypeSalary::getColumnName).collect(Collectors.toList());

            List<SalaryMonthEnd> salaryList = agencySalaryMultipleDao.getSalaryMonthEedSubmitByPersonId(column_name, agencyId, personId);
            if (list.size() > 0) {
                for (PersonTypeSalary personTypeSalary : list) {
                    Map<String, Object> map = new HashMap<>(3);

                    map.put("keyId", personTypeSalary.getSalaryId());//工资项表id
                    map.put("name", personTypeSalary.getSalaryName() + "：");//工资项名称
                    map.put("columnName",personTypeSalary.getColumnName());//工资项对应工资表字段
                    map.put("isCompute",personTypeSalary.getIsCompute());//计算项对应工资表字段
                    map.put("isStandard",personTypeSalary.getIsStandard()==null?0:personTypeSalary.getIsStandard());//是否标准对应工资表字段
                    map.put("isShow",personTypeSalary.getIsShow()==null?1:personTypeSalary.getIsShow());//是否标准对应工资表字段
                    if(salaryList.size()>0) {
                        map.put("id",salaryList.get(0).getId());//工资表id
                        map.put("value", converBeanFiledForObject(salaryList.get(0), "getS" + personTypeSalary.getColumnName().replaceAll("s", "")));//工资金额
                    }else{
                        map.put("id",null);//工资表id
                        map.put("value",0);
                    }
                    resultList.add(map);
                }
            }
        }
        return resultList;
    }
    /**
     *通过单位ID查询AgencyInfo表中is_submit_able字段值
     * @param agencyId
     * @return Integer
     */
    @Override
    public Integer getSubmitAble(String agencyId) {
        return  agencyInfoDao.getSubmitAble(agencyId);

    }

    @Override
    public List<String> getIsThirteen(String agencyId) {
        return  agencyInfoDao.getIsThirteen(agencyId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addBatch(String agencyId, UserDTO userDto)throws Exception {
        try{
        //查询单位 is_month_end='1'最大月份的数据
        List<AgencyVerify> agencyVerifyList=agencySalaryMultipleDao.getAgencyVerifyByAgencyId(agencyId);
        //查询月结历史表的数据
        List<SalaryHistory> historyList=agencySalaryMultipleDao.getHistoryList(agencyId,userDto.getProvince());
        //查询最大thirteen
        AgencyVerify  agencyVerifyThirteen=agencySalaryMultipleDao.getThirteen(agencyId);
           //如果当前agencyVerify>1的条数据说明已经增加批次
            if(agencyVerifyList.size()>1){
                for(AgencyVerify agencyVerify:agencyVerifyList){
                    if(agencyVerify.getIsMonthEnd().equals(0)){
                        //查看当前的批次是否月结月结走插入非月结提示无法新增批次
                        //return ApiResultDTO.error(null, "当前批次未月结无法继续生成批次，请当前批次处理完毕在新增批次");
                        throw new AppRuntimeException("当前批次未月结无法继续生成批次，请当前批次处理完毕在新增批次!");
                    }
                }
                for(AgencyVerify agencyVerify:agencyVerifyList){
                    //判断MonthEnd是否是否等于1并且最大批次是否等于查出的最大批次如果都符合插入
                  if(agencyVerify.getIsMonthEnd().equals(1)&&agencyVerify.getIsThirteen().equals(agencyVerifyThirteen.getIsThirteen())){
                      agencyVerify.setId(SysUtils.generateGuid());
                      agencyVerify.setBizKey(SysUtils.generateGuid());
                      agencyVerify.setCreateTime(String.valueOf(DateUtils.getCurrentTimeStamp()));
                      agencyVerify.setIsDeleted(0);
                      agencyVerify.setSalaryVerifiedInAgencyCode("0");
                      agencyVerify.setSalaryInfoVerifiedCode(null);
                      agencyVerify.setPersonInfoVerifiedCode("0");
                      agencyVerify.setAgencyInfoVerifiedCode("0");
                      agencyVerify.setIsSubmitInAgency(0);
                      agencyVerify.setIsSalarySubmit(0);
                      agencyVerify.setIsPersonSubmit(0);
                      agencyVerify.setIsAgencySubmit(0);
                      agencyVerify.setIsConfirmSubmit(0);
                      agencyVerify.setAuditExplain(null);
                      agencyVerify.setRemark(null);
                      agencyVerify.setIsSalaryChange(0);
                      agencyVerify.setAddPersonNum(0);
                      agencyVerify.setAddQuitPersonNum(0);
                      agencyVerify.setDeletePersonNum(0);
                      agencyVerify.setIsThirteen(agencyVerifyThirteen.getIsThirteen()+1);
                      agencyVerify.setIsPayDataCreated(0);
                      agencyVerify.setIsBankDataCreated(0);
                      agencyVerify.setIsAuto("0");
                      agencyVerify.setIsVerifyEnd(null);
                      agencyVerify.setIsPaymentAgency(1);
                      agencyVerify.setIsMonthEnd(0);
                      agencyVerify.setMofDivCode(userDto.getProvince());
                      //存入AgencyVerify表
                      agencySalaryMultipleDao.insetAgencyVerify(agencyVerify);
                      //存入MonthEndDouble表
                      agencySalaryMultipleDao.insetAgencyMonthEndDouble(historyList,agencyVerifyThirteen.getIsThirteen()+1);
                  }
                }
            }else if(historyList.size()>0){
                for(AgencyVerify agencyVerify:agencyVerifyList){
                agencyVerify.setId(SysUtils.generateGuid());
                agencyVerify.setBizKey(SysUtils.generateGuid());
                agencyVerify.setCreateTime(String.valueOf(DateUtils.getCurrentTimeStamp()));
                agencyVerify.setIsDeleted(0);
                agencyVerify.setSalaryVerifiedInAgencyCode("0");
                agencyVerify.setSalaryInfoVerifiedCode(null);
                agencyVerify.setPersonInfoVerifiedCode("0");
                agencyVerify.setAgencyInfoVerifiedCode("0");
                agencyVerify.setIsSubmitInAgency(0);
                agencyVerify.setIsSalarySubmit(0);
                agencyVerify.setIsPersonSubmit(0);
                agencyVerify.setIsAgencySubmit(0);
                agencyVerify.setIsConfirmSubmit(0);
                agencyVerify.setAuditExplain(null);
                agencyVerify.setRemark(null);
                agencyVerify.setIsSalaryChange(0);
                agencyVerify.setAddPersonNum(0);
                agencyVerify.setAddQuitPersonNum(0);
                agencyVerify.setDeletePersonNum(0);
                agencyVerify.setIsThirteen(agencyVerify.getIsThirteen()+1);
                agencyVerify.setIsPayDataCreated(0);
                agencyVerify.setIsBankDataCreated(0);
                agencyVerify.setIsAuto("0");
                agencyVerify.setIsVerifyEnd(null);
                agencyVerify.setIsPaymentAgency(1);
                agencyVerify.setIsMonthEnd(0);
                agencyVerify.setMofDivCode(userDto.getProvince());
                agencySalaryMultipleDao.insetAgencyVerify(agencyVerify);
                agencySalaryMultipleDao.insetAgencyMonthEndDouble(historyList,agencyVerifyThirteen.getIsThirteen()+1);
                }
            }else {
                throw new AppRuntimeException("当前无法生成批次，请在工资月结后新增批次!");
            }
        }catch(Exception e){
            logger.error(e.getMessage(), e);
            throw new AppRuntimeException(e.getMessage());
        }

    }

    @Override
    public AgencyVerify getAgencyVerifyByAgencyId(String agencyId) {
        return agencySalaryMultipleDao.getAgencyVerifyByAgencyIds(agencyId);
    }

    @Override
    public  Map<String, Object> getAgencyNameAndState(String agencyId) {
        return agencySalaryMultipleDao.selectAgencyNameAndState(agencyId);
    }

    @Override
    public void deletedDouble(String agencyId) {
        agencySalaryMultipleDao.deletedDouble(agencyId);
    }

    @Override
    public AgencyVerify getAgencyVerifyBizKey(String agencyId) {
          return agencySalaryMultipleDao.getAgencyVerifyBizKey(agencyId);
    }

    @Override
    public Integer getPaidWagesCount(String agencyId, UserDTO userDTO) {
            //查询控制 是否允许为0上报工资
            String zeroAbles= agencySalaryMultipleDao.getZeroAbles(userDTO.getProvince());
            if("null".equals(zeroAbles)||null==zeroAbles){
                zeroAbles="1";
            }
            return salaryMonthEndDao.getPaidWagesCountDouble(agencyId,zeroAbles);
        }

}
